package com.example.framework.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.common.enums.CodeEnum;
import com.example.common.exception.ServiceException;
import com.example.system.entity.Order;
import com.example.system.mapper.OrderMapper;
import com.example.system.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Author 王鹤蒲
 * @Date 2024 02 27
 */

@Component
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
@Slf4j
public class OrderStatusMonitoringJob implements Job {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IOrderService iOrderService;

    @Autowired
    private Scheduler scheduler;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDetail jobDetail=context.getJobDetail();
        JobDataMap jobDataMap=jobDetail.getJobDataMap();
        String orderNo=jobDataMap.get("orderNo").toString();
        if(redisTemplate.hasKey(orderNo)){
          return ;
        }
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper=new LambdaQueryWrapper<Order>();
        orderLambdaQueryWrapper.eq(Order::getDelFlag,'0');
        orderLambdaQueryWrapper.eq(Order::getOrderNo,orderNo);
        orderLambdaQueryWrapper.eq(Order::getStatus,"0");
        if(orderMapper.exists(orderLambdaQueryWrapper)){
            LambdaUpdateWrapper<Order> orderLambdaUpdateWrapper=new LambdaUpdateWrapper<>();
            orderLambdaUpdateWrapper.eq(Order::getOrderNo,orderNo);
            orderLambdaUpdateWrapper.set(Order::getStatus,"-1");
            orderMapper.update(new Order(),orderLambdaUpdateWrapper);
            String email=jobDataMap.get("email").toString();
            String subject="挂号订单支付超时提醒";
            String message="您的挂号订单（订单号："+orderNo+"）因超过规定支付时间，系统已将其自动取消。";
            iOrderService.sendMailReminder(email,subject,message);
        }
        try {
            JobKey jobKey=jobDetail.getKey();
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            throw new ServiceException(CodeEnum.TIMING_TASK_ERROR.getCode(),CodeEnum.TIMING_TASK_ERROR.getMsg());
        }
    }
}
